var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var WxParse = require('../../utils/wxParse/wxParse.js');
var shopInfo = require('../../components/shopInfo/index.js');
var app = getApp();

Page({
  data: {
    dataLoaded: false,

    swiperHei: 0,
    curSwiperIndex: 0,
    shop: {},
    goodsId: '',
    skuList: [],
    curSkuItem: null,
    isLogin: false,
    dataLoaded: false,

    //弹出浮层
    panel: {
      type: 1, //1.立即购买2.加入购物车
      isShow: false,
      aimation: {},
      opacityAnimation: {},
      height: 0,
      phone: '',
      yzm: '',
      yzmTime: 0,
    },

    //计数器
    counter: {
      number: 1,
      minusDisabled: false,
      addDisabled: false,
    },
  },

  onLoad: function (options) {
    this.setData({
      isLogin: !!app.getUserSid(),
      goodsId: options.goodsId,
    });

    // this._initSizeByWin();
    this._initPage();
  },

  onshow() {
    this.setData({
      isLogin: !!app.getUserSid(),
    });
  },

  onShareAppMessage: function () {
    return {
      title: this.data.shop.shareTitle,
      path: "pages/index/index"
    }
  },

  /**
   * 根据图片高度设置swiper高度
   */
  _swiperImgLoaded: function (evt) {
    if (this.data.swiperHei > 0) {
      return;
    }
    var self = this;
    var ratio = evt.detail.height / evt.detail.width;

    wx.getSystemInfo({
      success: function (res) {
        self.setData({
          dataLoaded: true,
          swiperHei: res.windowWidth * ratio
        });
      }
    });
  },

  /**
    * 调用电话接口
    */
  _doTel: function () {
    wx.makePhoneCall({
      phoneNumber: this.data.shop.phone
    })
  },

  /**
   * 打开店铺地址定位
   */
  _toMap() {
    var shop = this.data.shop;

    ajax.G('/openapi/CAddress/getLocation', {
      addr: shop.address
    }, function (data) {
      var addressInfo = JSON.parse(data.result)['result'];

      wx.openLocation({
        latitude: addressInfo.location.lat,
        longitude: addressInfo.location.lng,
        name: shop.name,
        address: shop.address
      })
    })
  },

  /**
   * 请求页面数据
   */
  _initPage() {
    var $this = this;

    ajax.G('/openapi/CHome/goods_detail', {
      goodsId: this.data.goodsId,
    }, function (data) {
      var d = data['result'];
      var skuJson = JSON.parse(d.skuJson);
      var imageUrls = [];

      $this._goodsSku = d.goodsSku;
      $this._skuJson = JSON.parse(d.skuJson);

      (d.imageUrls || []).forEach(function (url) {
        if (url) {
          imageUrls.push(url);
        }
      });

      $this._setSkuList();
      $this._setSkuItem();

      if (d.goodsDetail) {
        WxParse.wxParse('article', 'html', d.goodsDetail, $this, 0);
      }
      shopInfo.init('shopInfoData', $this);
      $this.setData({
        dataLoaded: true,
        // shop: app.getShop(),
        goodsImg: d.imageUrl,
        goodsName: d.name,
        salePrice: d.salePrice,
        defaultSku: d.defaultSku,
        goodsSku: d.goodsSku,
        skuJson: JSON.parse(d.skuJson),
        imageUrls: imageUrls,
      });

      $this._resetCounter();
    });
  },

  /**
   * swiper切换时
   */
  _swiperChange: function (evt) {
    this.setData({
      curSwiperIndex: evt.detail.current,
    });
  },

  /**
   * 预览图片
   */
  _previewImg: function () {
    wx.previewImage({
      current: this.data.imageUrls[this.data.curSwiperIndex],
      urls: this.data.imageUrls,
    })
  },

  /**
   * 选择sku
   */
  _selectSku(evt) {
    var {groupIndex, skuIndex} = evt.target.dataset;
    var skuList = this.data.skuList;
    var groupObj = skuList[groupIndex];

    groupObj.skuArr.forEach(function (sku, index) {
      sku.selected = index == skuIndex;
    });

    this.setData({
      skuList: skuList,
    });

    this._setSkuItem();
    this._resetCounter();
  },

  /**
   * 立即购买
   */
  _buy: function () {
    this._showPanel(1);
  },

  /**
   * 确定下单
   */
  _confirmBuy() {
    var self = this;

    if (!self._validSubmit()) {
      return;
    }
    self._login(function () {
      quickBuy();
    });

    function quickBuy() {
      ajax.P('/openapi/CHome/showQuickBuy', {
        goodsId: self.data.goodsId,
        skuId: self.data.curSkuItem.skuId,
        amount: self.data.counter.number,
      }, function (data) {
        self._closePanel();
        wx.navigateTo({
          url: '../confirmOrder/confirmOrder?goodsId=' + self.data.goodsId + '&skuId=' + self.data.curSkuItem.skuId + '&amount=' + self.data.counter.number
        })
      });
    }
  },

  /**
   * 加入购物车
   */
  _addCart: function () {
    this._showPanel(2);
  },

  /**
   * 确定加入购物车
   */
  _confirmAddCart: function () {
    var self = this;

    if (!self._validSubmit()) {
      return;
    }
    self._login(function () {
      ajax.P('/openapi/CCart/add', {
        goodsId: self.data.goodsId,
        skuId: self.data.curSkuItem.skuId,
        amount: self.data.counter.number,
      }, function (data) {
        self._closePanel();
        util.showOK('加入购物车成功');
      });
    });
  },

  _validSubmit() {
    var self = this;

    if (!self.data.isLogin && !self.data.panel.phone) {
      util.alert('请输入手机号');
      return false;
    } else if (!self.data.isLogin && !self.data.panel.yzm) {
      util.alert('请输入验证码');
      return false;
    } else if (self.data.counter.number <= 0) {
      util.alert('请输入正确的商品数量');
      return false;
    } else if (self.data.counter.number > self.data.curSkuItem.amount) {
      util.alert('商品库存不足哦');
      return false;
    }
    return true;
  },

  /**
   * 登陆
   */
  _login(cb) {
    var self = this;
    var panel = self.data.panel;

    if (app.getUserSid()) {
      cb && cb();
    } else {
      ajax.P('/openapi/CBrand/bandPhone', {
        code: panel.yzm,
        phone: panel.phone,
        openId: app.getOpenId(),
      }, function (data) {
        var userSid = data.result.userSid;

        app.setUserSid(userSid);
        self.setData({ isLogin: !!userSid });
        cb && cb();
      });
    }
  },

  /**
   * 手机号输入
   */
  _phoneInput: function (evt) {
    var panel = this.data.panel;

    panel.phone = evt.detail.value;
    this.setData({ panel });
  },

  /**
   * 验证码输入
   */
  _yzmInput: function (evt) {
    var panel = this.data.panel;

    panel.yzm = evt.detail.value;
    this.setData({ panel });
  },

  /**
   * 获取验证码
   */
  _getYzm() {
    if (!this.data.panel.phone) {
      return util.alert('请输入手机号');
    }
    ajax.P('/openapi/CBrand/sendMsg', {
      phone: this.data.panel.phone,
    }, function (data) {
      this._timerDown(60);
    }.bind(this));
  },

  /**
   * 倒计时
   */
  _timerDown: function (time) {
    var panel = this.data.panel;

    panel.yzmTime = --time;
    this.setData({ panel });
    if (time == 0) {
      return;
    }
    setTimeout(function () {
      this._timerDown(time);
    }.bind(this), 1000);
  },

  /**
   * 展示购买浮层
   */
  _showPanel(ty) {
    var $this = this;
    var panel = this.data.panel;

    panel.type = ty;
    $this.animation = wx.createAnimation(
      {
        duration: 500,
        timingFunction: "ease-out"
      }
    );
    $this.opacityAnimation = wx.createAnimation(
      {
        duration: 500,
        timingFunction: "ease-out"
      }
    );

    panel.isShow = true;
    $this.setData({
      panel
    });

    setTimeout(function () {
      $this.animation.translateY(0).step();
      $this.opacityAnimation.opacity(1).step();

      panel.animation = $this.animation.export();
      panel.opacityAnimation = $this.opacityAnimation.export();

      $this.setData({
        panel
      });
    }, 0);
  },

  /**
   * 关闭购买浮层
   */
  _closePanel() {
    var $this = this;
    var panel = this.data.panel;

    $this.animation.translateY('100%').step();
    $this.opacityAnimation.opacity(0).step();

    panel.animation = $this.animation.export();
    panel.opacityAnimation = $this.opacityAnimation.export();

    $this.setData({
      panel
    })
    setTimeout(function () {
      panel.isShow = false;
      $this.setData({
        panel
      });
    }, 500)
  },

  /**
   * sku变化时，重围计数器
   */
  _resetCounter() {
    var amount = +this.data.curSkuItem.amount; //当前库存
    var counter = this.data.counter;

    if (counter.number > amount) {
      counter.number = amount;
    }

    counter.minusDisabled = counter.number <= 0;
    counter.addDisabled = counter.number >= amount;
    this.setData({
      counter
    });
  },

  /**
   * 计数器+
   */
  _add: function (evt) {
    var counter = this.data.counter;
    var max = evt.target.dataset.max;

    if (max != undefined && ++counter.number > max) {
      counter.number = max;
    }
    if (counter.number == max) {
      counter.addDisabled = true;
    }else{
      counter.minusDisabled = false;
    }
    this.setData({
      counter,
    });
  },

  /**
   * 计数器-
   */
  _minus: function (evt) {
    var counter = this.data.counter;
    var min = evt.target.dataset.min;

    if (min != undefined && --counter.number < min) {
      counter.number = min;
    }
    if (counter.number < 0) {
      counter.number = 0;
    }
    if (counter.number == min) {
      counter.minusDisabled = true;
    } else {
      counter.addDisabled = false;
    }

    this.setData({
      counter
    });
  },

  /**
   * 计数量input输入
   */
  _changeNum: function (evt) {
    var val = parseInt(evt.detail.value) || 1;
    var counter = this.data.counter;

    counter.number = val;
    this.setData(counter);
  },

  /**
   * 根据窗口大小，初始化组件宽高
   */
  _initSizeByWin: function () {
    var $this = this;
    // var panel = this.data.panel;

    wx.getSystemInfo({
      success: function (res) {
        // panel.height = res.windowHeight * 0.85;
        $this.setData({
          swiperHei: res.windowWidth * 0.53,
          // panel
        });
      }
    })
  },

  /**
   * 重组sku列表数据结构
   */
  _setSkuList() {
    var goodsSku = this._goodsSku;
    var skuList = this.data.skuList;

    Object.keys(goodsSku).forEach(function (key) {
      var skuArr = goodsSku[key];
      var skuItem = {
        text: key,
        skuArr: [],
      }

      skuArr.forEach(function (text, index) {
        skuItem.skuArr.push({
          text: text,
          selected: index == 0 ? true : false
        })
      });
      skuList.push(skuItem)
    });

    this.setData({
      skuList: skuList
    });
  },

  /**
   * 设置当前选中sku
   */
  _setSkuItem() {
    var skuList = this.data.skuList;
    var skuJson = this._skuJson;
    var curSkuItem;
    var selectedObj = {};

    skuList.forEach(function (group) {
      group.skuArr.some(function (skuItem) {
        if (skuItem.selected) {
          selectedObj[group.text] = skuItem.text;
          return true;
        }
      });
    });

    skuJson.some(function (sku) {
      if (sku.skuValue == JSON.stringify(selectedObj)) {
        curSkuItem = {
          skuId: sku.skuId,
          price: sku.price,
          amount: sku.amount,
        };
        return true;
      }
    });
    this.setData({
      curSkuItem: curSkuItem,
    });
  },

});